#include "InputEventFilter.h"
#include "InputEvent.h"
#include <QKeyEvent>
#include <QDebug>

InputEventFilter::InputEventFilter(unsigned int inputsRequested)
  : mInputManager(InputManager::inputManager(inputsRequested)),
    mInputMapping(0)
{
  mInputManager.registerCallback(this);
  qRegisterMetaType<ButtonType>();
  qRegisterMetaType<HalfAxisType>();
}

InputEventFilter::~InputEventFilter()
{
  mInputManager.deregisterCallback(this);
}

void InputEventFilter::installInputMapping(InputMapping *mapping)
{
  mInputMapping = mapping;
}

void InputEventFilter::axisEvent(unsigned int input, unsigned int axis, int value)
{
  HalfAxisType ha;
  ha.mType = HalfAxisType::TYPE_AXIS;
  ha.mGamepadAxis = axis;
  ha.mGamepadNumber = input;
  if (value < 0)
  {
    ha.mDirection = HalfAxisType::DIRECTION_NEG;
  }
  else if (value == 0)
  {
    ha.mDirection = HalfAxisType::DIRECTION_NONE;
  }
  else
  {
    ha.mDirection = HalfAxisType::DIRECTION_POS;
  }
  emit axisMovement(ha, value);
  if (mInputMapping)
  {
    mInputMapping->movement(ha, value);
  }
}

void InputEventFilter::buttonEvent(unsigned int input, unsigned int button, bool pressed)
{
  ButtonType bt(ButtonType::TYPE_GAMEPAD, button, input);
  if (pressed)
  {
    emit buttonPress(bt);
    if (mInputMapping)
    {
      mInputMapping->press(bt);
    }
  }
  else
  {
    emit buttonRelease(bt);
    if (mInputMapping)
    {
      mInputMapping->release(bt);
    }
  }
}

bool InputEventFilter::eventFilter(QObject *o, QEvent *event)
{
  QKeyEvent* e(dynamic_cast<QKeyEvent*>(event));
  if (e)
  {
    Qt::Key k(static_cast<Qt::Key>(e->key()));
    ButtonType bt(ButtonType(ButtonType::TYPE_KEYBOARD, k));
    if (e->type() == QEvent::KeyPress)
    {
      emit buttonPress(bt);
      if (mInputMapping)
      {
        mInputMapping->press(bt);
      }
    }
    else if (e->type() == QEvent::KeyRelease)
    {
      emit buttonRelease(bt);
      if (mInputMapping)
      {
        mInputMapping->release(bt);
      }
    }
  }

  return QObject::eventFilter(o, event);
}
